'use strict';

const Controller = require('egg').Controller;

class HomeController extends Controller {
    // 摄影师信息添加
    async add() {
        let { ctx, app } = this;

        let { Sgrade, Sname, Sage, Smoney, Snumber } = this.ctx.request.body;
		
		// 参数验证
		const paramVerification = await ctx.parameter({ Sgrade, Sname, Sage, Smoney, Snumber  })
		if(paramVerification !== ''){
		    return ctx.apiFail(paramVerification);
		}

        // 判断当前昵称是否存在
        const resSelect = await app.mysql.get('Sheyinshi', { Sname });
        if(resSelect !== null){
            return ctx.apiFail('注册失败 改姓名已存在');
        }
		
		const created_at = (new Date()).getTime();

        // 数据库插入
        const result = await app.mysql.insert('Sheyinshi', { Sgrade, Sname, Sage, Sjobtime:created_at, Smoney, Snumber });

        if(result.affectedRows !== 1){
            return ctx.apiFail('添加失败');
        }

        return ctx.apiSuccess('添加成功');
    }
	
	// 信息查询
	async sheyinshiList(){
		const { ctx, app } = this;
		
		const { pages, pageNumber } = ctx.query;
		
		// 参数验证
		const paramVerification = await ctx.parameter({ pages, pageNumber })
		if(paramVerification !== ''){
		    return ctx.apiFail(paramVerification);
		}
		
		// 查询数据总记录数
		const resultsCount = await this.app.mysql.query('SELECT count(*) FROM Sheyinshi');
		const sum = resultsCount[0]['count(*)']; // 总页数
		
		// 分页查询数据
		const res = await this.app.mysql.select('Sheyinshi', { 
		  limit: pages*1, // 每页数据量
		  offset: pageNumber*1, // 页码
		});
		
		const data = {
			list:res, // 数据
			sum, // 总记录数
			SumPages: Math.ceil(sum/pages*1), // 总页数
			pageNumber: pageNumber*1, // 当前页码 
		}
		
		return ctx.apiSuccess(data);
		
	}
	
	// 修改
	async update(){
		const { ctx, app } = this;
		let { Sheyinshiid, Sgrade, Sname, Sage, Sjobtime, Smoney, Snumber } = ctx.request.body;
		
		// 参数验证
		const paramVerification = await ctx.parameter({ Sheyinshiid, Sgrade, Sname, Sage, Sjobtime, Smoney, Snumber })
		if(paramVerification !== ''){
		    return ctx.apiFail(paramVerification);
		}
		
		// 要修改的值
		const row = {
		  Sgrade, Sname, Sage, Sjobtime, Smoney, Snumber
		};
		
		// 修改条件
		const options = {
		  where: {
		    Sheyinshiid
		  }
		};
		// 修改
		const result = await this.app.mysql.update('Sheyinshi', row, options);
		
		// 判断是否成功
		if(result.affectedRows !== 1){
			return ctx.apiFail('更改失败');
		}
		return ctx.apiSuccess('更改成功');
	}
	
	// 删除
	async del(){
		const { ctx, app } = this;
		let { Sheyinshiid } = ctx.request.body;
		// 参数验证
		const paramVerification = await ctx.parameter({ Sheyinshiid })
		if(paramVerification !== ''){
		    return ctx.apiFail(paramVerification);
		}
		
		// 删除
		const result = await this.app.mysql.delete('Sheyinshi', { Sheyinshiid });
		
		// 判断是否成功
		if(result.affectedRows !== 1){
			return ctx.apiFail('删除失败');
		}
		
		return ctx.apiSuccess('删除成功');
	}
}

module.exports = HomeController;
